package com.ylxn.sqlSession;

import com.ylxn.pojo.Configuration;
import com.ylxn.pojo.MappedStatement;

import java.lang.reflect.*;
import java.sql.SQLException;
import java.util.List;

public class DefaultSqlSession implements SqlSession{

    Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) {
        //将完成对simpleExecutor里的query方法的调用
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        List<Object> query = simpleExecutor.query(configuration, mappedStatement, params);
        return (List<E>) query;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) {
        List<Object> objects = selectList(statementId, params);
        if (objects.size()==1){
            return (T) objects.get(0);
        }else {
            throw new RuntimeException("查询结果为空或者查询结果不符");
        }
    }

    @Override
    public int save(String statementId, Object... params) throws SQLException, NoSuchFieldException, IllegalAccessException {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        int save = simpleExecutor.save(configuration, mappedStatement, params);
        return save;
    }

    @Override
    public int update(String statementId, Object... params) throws SQLException, NoSuchFieldException, IllegalAccessException {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        int update = simpleExecutor.update(configuration, mappedStatement, params);
        return update;
    }

    @Override
    public int delete(String statementId, Object... params) throws SQLException, NoSuchFieldException, IllegalAccessException {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        int delete = simpleExecutor.delete(configuration, mappedStatement, params);
        return delete;    }


    /**
     * 使用jdk动态代理，来为dao生成代理对象，并返回结果
     * @param mapperClass
     * @param <T>
     * @return
     */
    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        Object o = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //1,底层还是去执行JDBC代码，根据不同情况，来调具体的方法
                //2，1-准备参数statementID：sql的唯一标识，：namespace.id=接口的全限定类型加方法名
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();
                String statementId = className+"."+methodName;
                //2,准备参数2：params：args
                //2.1,获取代理对象返回值类型
                System.out.println(statementId);
                Type type = method.getGenericReturnType();
                String methodNameCrud = method.getName();
               if ("save".indexOf(methodName)>0){
                   return save(statementId, args);
               }else if ("update".indexOf(methodName)>0){
                   return update(statementId,args);
               }
               else if ("delete".indexOf(methodName)>0){
                   return delete(statementId,args);
               }
               else if (type instanceof ParameterizedType){
                    List<Object> objects = selectList(statementId, args);
                    return objects;
                }
                return selectOne(statementId,args);
            }
        });
        return (T) o;
    }
}
